Skip to main content

Structs

A struct (short for structure) is a custom data type that lets you group related data together under one name, with named fields.

Think of a struct as:

A blueprint for an object (without OOP inheritance)

struct User {
username: String,
email: String,
age: u32,
}
  • User → struct name
  • Fields have names and types
  • Groups logically related data

Key Characteristics of Structs

FeatureStruct
FieldsNamed
TypesCan be different
SizeFixed
OwnershipOwns its data
MutabilityOptional
MemoryStack (by default)

Creating Struct Instances

let user1 = User {
username: String::from("alice"),
email: String::from("alice@example.com"),
age: 25,
};

Mutable Struct

let mut user2 = User {
username: String::from("bob"),
email: String::from("bob@example.com"),
age: 30,
};

user2.age = 31;

📌 Entire instance must be mut.

Accessing Struct Fields

println!("{}", user1.username);
println!("{}", user1.age);

Dot (.) notation.

Struct Update Syntax

let user3 = User {
username: String::from("charlie"),
..user1
};

Reuses remaining fields from user1.

Ownership note:

  • Fields like String are moved
  • user1 may become partially unusable

Functions Using Structs

Passing Structs (Borrowing)

fn print_user(user: &User) {
println!("{} ({})", user.username, user.age);
}

Usage:

print_user(&user2);

Returning Structs

fn create_user(name: String, email: String) -> User {
User {
username: name,
email,
age: 18,
}
}

Methods and impl Blocks

Adding Methods to Structs

impl User {
fn greet(&self) {
println!("Hello, {}", self.username);
}
}

Usage:

user2.greet();

&self borrows the instance.

Associated Functions (Like Constructors)

impl User {
fn new(username: String, email: String) -> User {
User {
username,
email,
age: 0,
}
}
}

Usage:

let user = User::new(
String::from("dave"),
String::from("dave@example.com"),
);

Tuple Structs

struct Color(u8, u8, u8);

Usage:

let red = Color(255, 0, 0);

Access:

println!("{}", red.0);

Like tuples but with a name.

Unit-Like Structs

struct Marker;

Used when:

  • You need a type but no data
  • Marker traits or configurations

Structs vs Tuples

FeatureStructTuple
Field names✅ Yes❌ No
ReadabilityHighLow
Best forComplex dataTemporary grouping

Ownership and Struct Fields

struct Book {
title: String,
pages: u32,
}

let book1 = Book {
title: String::from("Rust Book"),
pages: 500,
};

let book2 = book1;
// book1 is no longer usable

Struct follows ownership rules per field.

Structs with References (Lifetimes)

struct Article<'a> {
title: &'a str,
content: &'a str,
}

Used when struct does not own data.